import { AdminService } from './../service/admin/admin.service';
import { Injectable, NestMiddleware } from '@nestjs/common';
import config from 'src/config/config';

@Injectable()
export class AdminauthMiddleware implements NestMiddleware {
    constructor(private readonly adminService: AdminService) {}
    async use(req: any, res: any, next: () => void) {
        const whiteList = [
            { url: '/admin/login', method: 'POST' },
            { url: '/admin/login/register', method: 'POST' },
            { url: '/admin/login/code', method: 'GET' },
            { url: '/admin/login/logout', method: 'POST' },
            { url: '/admin/login/getTestData', method: 'GET' },
            { url: '/admin/shopSetting', method: 'GET' },
        ];
        console.log(req.baseUrl, req.method);
        if (whiteList.some((item) => item.url === req.baseUrl && item.method.toLowerCase() === req.method.toLowerCase())) {
            next();
        } else {
            if (req.signedCookies[config.authCookieKey]) {
                const checkededAuthResult = await this.adminService.checkAuth(req);
                if (checkededAuthResult) {
                    next();
                } else {
                    res.send({
                        code: 403,
                        message: '暂无权限',
                    });
                }
            } else {
                res.send({
                    code: 401,
                    message: '请登录',
                });
            }
        }
    }
}
